package com.baomidou.springwind.test.IO;

import java.io.*;
import java.util.Random;

/**
 * Created by Administrator on 2017/3/12.
 */

class Data implements Serializable{
    private int n;

    public Data(int n) {
        this.n = n;
    }

    @Override
    public String toString() {
        return Integer.toString(n);
    }
}

public class Worm implements Serializable {
    private static Random rand = new Random(47);
    private Data[] data = {new Data(rand.nextInt(10)),
            new Data(rand.nextInt(10)), new Data(rand.nextInt(10))};
    private Worm next;
    private char c;

    public Worm(int n, char x) {
        System.out.println("Worm Constructor: " + n);
        c = x;
        if (--n > 0) {
            next = new Worm(n, (char) (x + 1));
        }
    }

    public Worm() {
        System.out.println("Worm Default Constructor");
    }

    @Override
    public String toString() {
        StringBuilder s = new StringBuilder(":");
        s.append(c);
        s.append("(");
        for (Data d : data)
            s.append(d);
        s.append(")");
        if (next != null) {
            s.append(next);
        }
        return s.toString();
    }

    public static void main(String[] args) throws IOException, ClassNotFoundException {
        Worm worm = new Worm(6,'a');
        System.out.println("worm:" + worm);
        ObjectOutputStream out = new ObjectOutputStream(
                new FileOutputStream("F:\\code\\SpringWind\\SpringWind\\src\\main\\java\\com\\baomidou\\springwind\\test\\IO\\Worm.out"));
        out.writeObject("Worm storage\n");
        out.writeObject(worm);
        out.close();

        ObjectInputStream ois = new ObjectInputStream(
                new FileInputStream("F:\\code\\SpringWind\\SpringWind\\src\\main\\java\\com\\baomidou\\springwind\\test\\IO\\Worm.out"));
        String s = (String) ois.readObject();
        Worm worm1 = (Worm) ois.readObject();
        System.out.println("worm1:"+worm1);
    }
}
